#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int data[5];
int written = 0;
pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER;
void * thread1(void * arg)
{
    for(int times = 0; times < 5; times ++)
    {
        // lock and write
        while(written);
        pthread_mutex_lock(&mux);
        for(int i = 0;i<5;i++)
        {
            data[i] = random()%10;
        }
        written = 1;
        pthread_mutex_unlock(&mux);
    }
}

void * thread2(void * arg)
{
    for (int times = 0; times < 5; times++)
    {
        // lock and calculate sum
        int sum;
        sum = 0;
        while(!written);
        pthread_mutex_lock(&mux);
        for(int i = 0;i<5;i++)
        {
            sum += data[i];
            printf("%d ",data[i]);
        }
        putchar('\n');
        written = 0;
        printf("Sum: %d\n",sum);
        pthread_mutex_unlock(&mux);
    }
}

int main()
{
    pthread_t t1,t2;
    pthread_create(&t1,NULL,thread1,NULL);
    pthread_create(&t2,NULL,thread2,NULL);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    return 0;
}
